package net.seehope.foodie.code;

import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.context.request.ServletWebRequest;

import net.seehope.foodie.properties.ProjectConstant;

public abstract class AbstractValidateCodeProcessor<C extends ValidateCode> implements ValidateCodeProcessor{

	@Autowired
	private Map<String, ValidateCodeGenerator> validateCodeGenerator;
	
	private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
	
	@Override
	public void create(ServletWebRequest request) throws Exception {
		//生成
		C validateCode = generator(request);
		
		//存储
		save(request,validateCode);
		
		//发送
		send(request,validateCode);
	}
	
	//创建
	//这里肯定返回的是验证码，但不知道返回的是哪种验证码，先返回C
	public C generator(ServletWebRequest request) {
		
		C validateCode = null;
		
		Set<String> keySet = validateCodeGenerator.keySet();
		
		for (String string : keySet) {
			System.out.println("key:"+ string + "getType:" + getType());
			if(StringUtils.containsIgnoreCase(string, getType())) {
				validateCode = (C) validateCodeGenerator.get(string).generator();
			}
		}

		return validateCode;
		
	}
	
	//存储，目前还是存在session
	public void save(ServletWebRequest request,C validateCode) {
		sessionStrategy.setAttribute(request,
				StringUtils.toRootUpperCase(getType()+ProjectConstant.CODE_IN_SESSION_SUFFIX), validateCode);
		
	}
	
	//发送(交给子类去实现)
	protected abstract void send(ServletWebRequest request,C validateCode) throws Exception;
	
	//取巧的方法:父类不知道如何实现的逻辑，空出来交给子类实现
	
	//要求子类返回一个实现的类型，比如如image或sms
	protected abstract String getType();
	

	@Override
	public void validate(ServletWebRequest request) {
		
		
	}

}
